import os
import subprocess
import json
import time

from Global import MulatorInfoStruct


class LeiDianMulator:
    def __init__(self, ldconsole):
        """
        初始化雷电模拟器管理类
        :param ld_path: 雷电模拟器安装路径
        """
        self.ldconsole = ldconsole

    def _execute_command(self, command):
        """
        执行adb命令并返回结果
        :param command: 完整的命令列表
        :return: (returncode, stdout, stderr)
        """
        try:
            process = subprocess.Popen(
                command,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                text=True,
                encoding='utf-8'
            )
            stdout, stderr = process.communicate()
            return process.returncode, stdout, stderr
        except Exception as e:
            return -1, "", str(e)
    def GetAllMulatorInfo(self):
        """
        获取指定序号模拟器的信息
        :param index: 模拟器序号
        :return: 模拟器信息字典，失败返回None
        """
        cmd = [self.ldconsole, "list2"]
        returncode, stdout, stderr = self._execute_command(cmd)
        mumu = MulatorInfoStruct()
        if returncode == 0:
            hangArr = stdout.split("\r")
            for hang in hangArr :
                print(hang)
        return mumu
    def GetMulatorInfo(self, index):
        """
        获取指定序号模拟器的信息
        :param index: 模拟器序号
        :return: 模拟器信息字典，失败返回None
        """
        cmd = [self.ldconsole, "list3", "-index", str(index)]
        returncode, stdout, stderr = self._execute_command(cmd)
        mumu = MulatorInfoStruct()
        if returncode == 0:
            try:
                 stdout.split(",")
            except json.JSONDecodeError:
                # 如果不是JSON格式，返回原始输出
                return mumu
        return mumu
    def Launch(self, index,package=None):
        """
        启动指定模拟器
        :param index: 模拟器序号
        :return: bool
        """
        if package==None:
            cmd = [self.ldconsole, "control", "-v", str(index),"launch"]
        else:
            cmd = [self.ldconsole, "control", "-v", str(index), "launch","-pkg",package]
        returncode, stdout, stderr = self._execute_command(cmd)
        return returncode == 0

    def Shutdown(self, index):
        """
        停止指定模拟器
        :param index: 模拟器序号
        :return: bool
        """
        cmd = [self.mumu_manager, "control", "-v", str(index),"shutdown"]
        returncode, stdout, stderr = self._execute_command(cmd)
        return returncode == 0
    def execute_shell(self, index, command):
        """
        在指定模拟器中执行shell命令
        :param index: 模拟器序号
        :param command: shell命令
        :return: (returncode, stdout, stderr)
        """
        return self._execute_command([self.ldconsole, "adb", "--index", str(index), "--command", command])

    def is_app_installed(self, index, package_name):
        """
        检查指定应用是否已安装
        :param index: 模拟器序号
        :param package_name: 应用包名
        :return: bool
        """
        returncode, stdout, stderr = self.execute_shell(
            index, f"pm list packages {package_name}"
        )
        return returncode == 0 and package_name in stdout

    def launch_app(self, index, package_name):
        """
        启动指定应用
        :param index: 模拟器序号
        :param package_name: 应用包名
        :return: bool
        """
        returncode, stdout, stderr = self._execute_command(
            [self.ldconsole, "launch", "--index", str(index), "--packagename", package_name]
        )
        return returncode == 0

    def is_app_active(self, index, package_name):
        """
        检查指定应用是否处于前台活动状态
        :param index: 模拟器序号
        :param package_name: 应用包名
        :return: bool
        """
        returncode, stdout, stderr = self.execute_shell(
            index, "dumpsys window windows | grep -E 'mCurrentFocus'"
        )
        return returncode == 0 and package_name in stdout